package top.starp.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class FileUtil {
    public static String readAll(Scanner scanner) {
        StringBuilder res = new StringBuilder();
        while (scanner.hasNextLine()) {
            String s = scanner.nextLine();
            res.append(s).append("\n");

        }
        return res.toString();
    }

    public static void main(String[] args) throws FileNotFoundException {
//        java 遍历文件夹
        String path = "./";        //要遍历的路径
        File rootDir = new File(path);        //获取其file对象
        File[] files = rootDir.listFiles();    //遍历path下的文件和目录，放在File数组中
        for (File file : files) {                    //遍历File[]数组
            if (!file.isDirectory()) {
//                加上 txt 后缀
                //若非目录(即文件)，则打印
                System.out.println(file);
                try (Scanner scanner = new Scanner(file)) {
//                    String s = scanner.nextLine();
                    String data = readAll(scanner);
                    String absolutePath = file.getAbsolutePath();
                    String outAbsPath = absolutePath + ".txt";
                    try (FileWriter fileWriter = new FileWriter(outAbsPath)) {
                        fileWriter.write(data);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

        }
//————————————————
//        版权声明：本文为CSDN博主「DcForever」的原创文章，遵循CC 4.0 BY-SA版权协议，转载请附上原文出处链接及本声明。
//        原文链接：https://blog.csdn.net/DCFANS/article/details/92840542

    }
}
